<template>
  <div>
    <div class="customer-tree">
      <a-card :bordered="false" class="tree-card">
        <div class="tree-container">
          <div class="common-tree">
            <a-tree
              v-model:expandedKeys="expandedKeys"
              v-model:selectedKeys="selectedKeys"
              :load-data="onLoadData"
              :tree-data="selectList"
              @select="onTreeSelect"
            />
          </div>
        </div>
      </a-card>
      <a-card :bordered="false" style="height: 830px; width: 1380px">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          bordered
          :pagination="pagination"
          class="mt-5"
          :row-class-name="
            (_record, index) =>
              index % 2 === 1 ? 'table-striped' : ''
          "
          :scroll="{ y: 550, x: 550 }"
          @expand="onLoadTable"
          :expandable="{ childrenColumnName: 'children' }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'type'">
              <a-tag
                :bordered="false"
                color="processing"
                v-if="record.type === 'page'"
                >页面</a-tag
              >
              <a-tag
                :bordered="false"
                color="geekblue"
                v-if="record.type === 'button'"
                >按钮</a-tag
              >
              <a-tag
                :bordered="false"
                color="orange"
                v-if="record.type === 'permission'"
                >权限</a-tag
              >
            </template>
            <template v-if="column.key == 'status'">
              <a-switch
                :checked="record.enabled"
                v-if="record.type === 'permission'"
                :checkedValue="1"
                :unCheckedValue="0"
                @change="
                  (checked) =>
                    handleSwitchChange(record, column, checked)
                "
              />
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, h } from 'vue';
import {
  getButtonAuth,
  getAccountButtonAuth,
  getUpdateAccountButtonAuth,
} from '#/api/core/auth';
import { getOperatorApi } from '#/api/core/statistical';
import { message } from 'ant-design-vue';
import type { TreeProps } from 'ant-design-vue';

// 定义数据类型
interface TreeNode {
  id: string;
  value: string;
  title: string;
  key: string;
  isLeaf?: boolean;
  children?: TreeNode[];
}

interface TableRecord {
  key: string;
  title: string;
  level?: number;
  id: string;
  type: string;
  enabled?: boolean;
  status?: string;
  children?: TableRecord[];
}

const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const treeData = ref<TreeProps['treeData']>([
  { title: 'Expand to load', key: '0' },
  { title: 'Expand to load', key: '1' },
  { title: 'Tree Node', key: '2', isLeaf: true },
]);
const columns = [
  {
    title: '页面/权限',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    customRender: ({ record }: any) => {
      if (record.type === 'permission') {
        return record.enabled
          ? h('span', { style: { color: '#52c41a' } }, '启用')
          : h('span', { style: { color: '#ff4d4f' } }, '禁用');
      }
      return '-';
    },
  },
];
const dataSource = ref<TableRecord[]>([]);
const selectList = ref<TreeNode[]>([]);
const currentSelectedUserId = ref<string | null>(null);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
      console.log(selectList.value);
    })
    .catch((error: any) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error: any) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  // 如果有选中的用户，重新加载表格数据
  if (currentSelectedUserId.value) {
    onTreeSelect([currentSelectedUserId.value]);
  }
};
const onTreeSelect = (e: any) => {
  console.log(e);
  // 保存当前选中的用户ID
  currentSelectedUserId.value = e[0];
  
  getButtonAuth({ userId: e[0] }).then((res: any) => {
    console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): TableRecord[] => {
      return tree.map((item: any) => {
        const processedItem: TableRecord = {
          key: item.id,
          title: item.title,
          level: item.level,
          id: item.id,
          type: 'page',
          children: undefined,
        };

        // 如果存在children，递归处理子节点
        if (item.children) {
          processedItem.children = processTreeData(item.children);
        }
        return processedItem;
      });
    };

    const treeData = processTreeData(res.data.data);
    dataSource.value = treeData;
    console.log(treeData);
  });
};
const onLoadTable = (expanded: boolean, record: any) => {
  console.log('表格展开状态:', expanded, '记录:', record);
  const userId = localStorage.getItem('userId');
  if (expanded && (!record.children || record.children.length === 0)) {
    // 根据记录的id获取权限数据
    getAccountButtonAuth({ userId: Number(userId), pageId: record.id })
      .then((res: any) => {
        console.log('获取权限数据:', res);

        // 将权限对象转换为表格子数据
        const permissionData = res.data.data;
        const buttonPermissions = [
          {
            key: 'adds',
            title: '新增权限',
            enabled: permissionData.adds,
          },
          {
            key: 'deletes',
            title: '删除权限',
            enabled: permissionData.deletes,
          },
          {
            key: 'exports',
            title: '导出权限',
            enabled: permissionData.exports,
          },
          {
            key: 'imports',
            title: '导入权限',
            enabled: permissionData.imports,
          },
          {
            key: 'selects',
            title: '查询权限',
            enabled: permissionData.selects,
          },
          {
            key: 'updates',
            title: '更新权限',
            enabled: permissionData.updates,
          },
        ];

        // 转换为表格数据格式
        const childData: TableRecord[] = buttonPermissions.map(
          (permission, index) => ({
            key: `${record.id}_${permission.key}`,
            title: permission.title,
            level: (record.level || 0) + 1,
            id: `${record.id}_${permission.key}`,
            type: 'permission',
            enabled: permission.enabled,
            // status: permission.enabled ? '启用' : '禁用',
            children: undefined,
          }),
        );

        // 更新数据源，将权限数据添加到对应的父记录中
        const updateDataSource = (data: TableRecord[]): TableRecord[] => {
          return data.map((item: TableRecord) => {
            if (item.id === record.id) {
              return {
                ...item,
                children: childData,
              };
            }
            if (item.children) {
              return {
                ...item,
                children: updateDataSource(item.children),
              };
            }
            return item;
          });
        };

        dataSource.value = updateDataSource(dataSource.value);
        console.log(dataSource.value);
      })
      .catch((error: any) => {
        console.error('获取权限数据失败:', error);
        message.error('获取权限数据失败');
      });
  }
};
// 处理开关状态变化
const handleSwitchChange = async (
  record: any,
  field: any,
  checked: string | number | boolean,
) => {
  console.log(record, field, checked);
  const result = record.key.replace(/[^_]*_/, '');
  console.log(result);
  // 删除字符串中的_前面的字符包括_

  try {
    const updateData = {
      userId: localStorage.getItem('userId'),
      [result]: checked ? 1 : 0,
      pageId: record.id.split('_')[0],
    };

    const response = await getUpdateAccountButtonAuth(updateData);

    if (response.data.code === 200) {
      // 更新本地数据
      record.enabled = checked;
      record.status = checked ? '启用' : '禁用';
      message.success('权限更新成功');
      
      // 重新加载表格数据以确保数据同步
      // setTimeout(() => {
      //   onSearch();
      // }, 100);
    } else {
      message.error(response.data.message || '权限更新失败');
    }
  } catch (error: any) {
    console.error('更新权限失败:', error);
    message.error('权限更新失败');
  }
};
</script>
<style scoped lang="scss">
.customer-tree {
  display: flex;
  .tree-card {
    width: 500px;
    height: 830px;
  }

  .tree-container {
    margin: 12px 0;
  }

  :deep(.ant-segmented-item-selected) {
    font-weight: bold;
    color: #006be6;
  }
}
.common-tree {
  :deep(.ant-tree-node-content-wrapper) {
    display: flex;
    align-items: center;
  }

  :deep(.ant-tree-icon__customize) {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
:deep(.customer-tree .tree-card) {
  overflow: auto !important;
}
</style>
